<?php

class Users_Controller_Admin_Index extends Light_Controller_Admin
{
	/**
	 * (non-PHPdoc)
	 * @see Light_Controller_Admin::init()
	 */
	public function init()
	{
		if ($this->getActionName() != 'login' && !$this->view->identity()) {
	        $this->view->redirect(array('module' => 'users', 'controller' => 'index', 'action' => 'login'), null, true);
	    }

	    if ($this->getActionName() != 'login' && !$this->view->isAdmin()) {
	        throw new Light_Exception('Access denied');
	    }
	}

	/**
	 * (non-PHPdoc)
	 * @see Light_Controller_Admin::addAction()
	 */
	public function addAction(Light_Db_Table_Row $item = null)
	{
	    $groupsModel = new Users_Model_Groups();

	    $this->view->assign('groups', $groupsModel->getGroups());

	    parent::addAction($item);
	}

	public function loginAction()
	{
	    if ($this->view->identity()) {
	        $this->view->redirect(array('action' => 'index'));
	    }

	    $data   = array();
	    $errors = array();

	    if ($this->getRequest()->isPost()) {
	        $model  = new Users_Model_Index();
	        $data   = $this->getRequest()->getPost();
	        $errors = $model->validate($data);
	        if (empty($errors)) {
	            if ($model->login($data['name'], $data['password'])) {
	                $this->view->redirect(array('action' => 'index'));
	            }
	            $errors['login'] = 'Invalid credentials';
	        }
	    }

	    $this->view->assign('data', $data);
	    $this->view->assign('errors', $errors);
	}

	public function logoutAction()
	{
		session_destroy();

		$this->view->redirect();
	}
}